import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import PropTypes from 'react-router/lib/PropTypes'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'
import * as SearchAction from '../actions/search'
import {WeaTable} from 'comsRedux'
import {
    WeaTop,
    WeaTab,
    WeaLeftTree,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
    WeaPopoverHrm
} from 'ecCom'

import {WeaErrorPage,WeaTools} from 'ecCom'
import {Button,Form} from 'antd'
import Immutable from 'immutable'
const createForm = Form.create;
const FormItem = Form.Item;
const is = Immutable.is;
const WeaTableAction = WeaTable.action;
import PreviewMeeting from './previewmeeting/index'
let _this = null;
class Search extends React.Component {
    static contextTypes = {
        router: PropTypes.routerShape
    }
    constructor(props) {
        super(props);
        _this = this;
    }
    componentDidMount() {//一些初始化请求
        const { actions } = this.props;
        //初始化高级搜索区域
        actions.initDatas();
        //初始化列表
        actions.doLoading();
    }
    componentWillReceiveProps(nextProps) {
    }
    
    componentWillUnmount() {
        //组件卸载时一般清理一些状态
    }
    
    render() {
        const { loading, title,actions,conditioninfo,showSearchAd,searchParamsAd,dataKey,topTab,previewMeetingId} = this.props;
        return (
            <div className="metting-search">
                
                        <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                            <WeaTop
                                title={title}
                                loading={loading}
                                icon={<i className='icon-search-search' />}
                                iconBgcolor='#55D2D4'
                                buttons={this.getButtons()}
                                buttonSpace={10}
                                showDropIcon={true}
                                dropMenuDatas={this.getRightMenu()}
                                onDropMenuClick={this.onRightMenuClick.bind(this)}
                            >
                                <WeaTab
                                    buttonsAd={this.getTabButtonsAd()}
                                    searchsBaseValue={searchParamsAd.names}
                                    searchType={['base','advanced']}
                                    setShowSearchAd={bool=>{actions.setShowSearchAd(bool)}}
                                    hideSearchAd={()=> actions.setShowSearchAd(false)}
                                    searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
                                    showSearchAd={showSearchAd}
                                    selectedKey={searchParamsAd.timeSag?searchParamsAd.timeSag:0}
                                    onSearch={v=>{actions.doLoading(searchParamsAd)}}
                                    onSearchChange={v=>{actions.saveFields({names:{name:'names',value:v}})}}
                                    keyParam="viewcondition"  //主键
                                    countParam="groupid" //数量
                                    onChange={this.changeData.bind(this)}
                                    datas={topTab}
                                />
                                {
                                    loading ? '加载中' :
                                    <WeaTable 
                                    sessionkey={dataKey} 
                                    hasOrder={true} 
                                    needScroll={false}
                                    getColumns = {this.getColumns}
                                    />
                                }
                            </WeaTop>
                        </WeaRightMenu>
                        <PreviewMeeting 
                            meetingId = {previewMeetingId}
                            onClose={(meetingid='')=>{actions.savePreviewMeetingId({meetingid:meetingid})}}
                        />
                
            </div>
        )
    }
    
    //右键菜单事件绑定
    onRightMenuClick(key){
        const {actions,searchParamsAd} = this.props;
        if(key == '0'){
            actions.doLoading(searchParamsAd);
            actions.setShowSearchAd(false);
        }else if(key == '1'){
            actions.doLoading();
            actions.setShowSearchAd(false);
        }
        
    }
    getColumns = (e)=>{
        const {actions} = this.props;
        let newColumns = '';
        newColumns = e.map(column => {
                let newColumn = column;
                newColumn.render = (text, record, index) => { //前端元素转义
                    let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
                    return(
                        newColumn.dataIndex == 'name'  ?
                         <div className="wea-url-name" style ={{cursor:'pointer'}} onClick={()=>{actions.savePreviewMeetingId({meetingid:record.id})}} dangerouslySetInnerHTML={{__html: valueSpan}} />
                        :
                         <div className="wea-url" dangerouslySetInnerHTML={{__html: valueSpan}} />

                    )
                }
                return newColumn;
            });
        return newColumns;
    }
    
    //右键菜单
    getRightMenu(){
        let btns = [];
        btns.push({
            icon: <i className='icon-Right-menu--search'/>,
            content:'搜索'
        });
        btns.push({
            icon: <i className='icon-Right-menu-Custom'/>,
            content:'重置'
        })
        return btns
    }
    //高级搜索group定义
    getSearchs() {
        return [
            (<WeaSearchGroup needTigger={true} title={this.getTitle()} showGroup={this.isShowFields()} items={this.getFields()}/>),
            (<WeaSearchGroup needTigger={true} title={this.getTitle(1)} showGroup={this.isShowFields(1)} items={this.getFields(1)}/>)
        ]
    }
    getTitle(index = 0) {
        const {conditioninfo} = this.props;
        return !isEmpty(conditioninfo) && conditioninfo[index].title
    }
    isShowFields(index = 0) {
        const {conditioninfo} = this.props;
        if(conditioninfo.length==0){
            return true;
        }
        return !isEmpty(conditioninfo) && conditioninfo[index].defaultshow
    }
    // 0 常用条件，1 其他条件
    getFields(index = 0) {
        const {conditioninfo} = this.props;
        const fieldsData = !isEmpty(conditioninfo) && conditioninfo[index].items;
        let items = [];
        forEach(fieldsData, (field) => {
            items.push({
                com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                    {WeaTools.switchComponent(this.props, field.key, field.domkey, field)}
                </FormItem>),
                colSpan:1
            })
        })
        return items;
    }
    //高级搜索底部按钮定义
    getTabButtonsAd() {
        const {actions,searchParamsAd} = this.props;
        return [
            (<Button type="primary" onClick={()=>{actions.doLoading(searchParamsAd);actions.setShowSearchAd(false)}}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.saveFields({})}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
    }
    getButtons() {
        let btns = [];
        return btns
    }
    changeData(theKey) {
        const {actions,searchParamsAd,fields} = this.props;
        searchParamsAd.timeSag = theKey;
        actions.saveFields({...fields,timeSag:{name:'timeSag',value:theKey}});
        actions.setShowSearchAd(false);
        actions.doLoading(searchParamsAd);
    }
}

//组件检错机制
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return(
            <WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
        );
    }
}

Search = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(Search);

//form 表单与 redux 双向绑定
Search = createForm(
    {
        onFieldsChange(props, fields) {
            props.actions.saveFields({ ...props.fields, ...fields });
        },
        mapPropsToFields(props) {
            return props.fields;
        }
    }
)(Search);


// 把 state map 到组件的 props 上
const mapStateToProps = state => {
    const { loading, title,conditioninfo,showSearchAd,searchParamsAd,fields,dataKey,topTab,previewMeetingId} = state.meetingSearch;
    return {
        loading,
        title,
        conditioninfo,
        showSearchAd,
        searchParamsAd,
        fields,
        dataKey,
        topTab,
        previewMeetingId,
    }
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
    return {
        actions: bindActionCreators(SearchAction, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Search);

